package com.naiterui.ehp.bs.patient.service.impl;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSONObject;
import com.naiterui.ehp.bp.bo.doctor.RecomPatientBO.AgeUnitEunm;
import com.naiterui.ehp.bp.bo.patient.FamilyBO;
import com.naiterui.ehp.bp.constants.CommonConstantEnum;
import com.naiterui.ehp.bp.domain.Patient;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bp.utils.lang.StringUtil;
import com.naiterui.ehp.bs.patient.dao.IPatientDao;
import com.naiterui.ehp.bs.patient.dao.IPatientFamilyDao;
import com.naiterui.ehp.bs.patient.domain.PatientFamily;
import com.naiterui.ehp.bs.patient.enums.FamilyRelationEnum;
import com.naiterui.ehp.bs.patient.exception.ExceptionCodes;
import com.naiterui.ehp.bs.patient.repository.IApPatientFamilyRepository;
import com.naiterui.ehp.bs.patient.service.IPatientFamilyService;
import com.naiterui.ehp.bs.patient.utils.LimitValueConfig;
import com.naiterui.ehp.bs.patient.utils.exception.PatientBusinessException;
import com.naiterui.ehp.bs.patient.vo.family.FamilyLiteVO;
import com.naiterui.ehp.bs.patient.vo.family.FamilyVO;
import com.naiterui.ehp.bs.patient.vo.family.param.FamilyParamVO;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 家庭成员业务逻辑实现层
 *
 * @since 2.18
 */
@Service
public class ApPatientFamilyServiceImpl implements IPatientFamilyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApPatientFamilyServiceImpl.class);
    @Autowired
    private IPatientFamilyDao patientFamilyDao;
    @Autowired
    private IPatientDao patientDao;

    @Autowired
    private IApPatientFamilyRepository patientFamilyRepository;
    /**
     * 本人
     */
    private static final int RELATION_ONESELF = 1;
    /**
     * 没有本人
     */
    private static final int RELATION_NOT_ONSELF = 2;
    /**
     * 没有家庭成员关系和本人信息（姓名、性别、年龄）
     */
    private static final int RELATION_NOT = 3;

    @Override
    public List<FamilyLiteVO> getFamilyListByPatientId(Long patientId) throws PatientBusinessException {
        List<PatientFamily> familyList = this.patientFamilyDao.getFamilyListByPatientId(patientId);
        List<FamilyLiteVO> familyVOList = new ArrayList<>();
        if (familyList != null && familyList.size() > 0) {
            FamilyLiteVO litevo = null;
            for (PatientFamily family : familyList) {
                litevo = new FamilyLiteVO();
                BeanUtils.copyProperties(family, litevo);
                this.setFamilyLiteVOAge(litevo, family.getBirth());
                familyVOList.add(litevo);
            }
        }
        return familyVOList;
    }

    @Override
    public List<FamilyBO> getDrFamilyList(List<Long> familyIds) throws PatientBusinessException {
        Iterable<PatientFamily> iterable = this.patientFamilyRepository.findByIdInAndVisible(familyIds, PatientFamily.VISIBLE_YES);
        List<FamilyBO> bos = new ArrayList<>();
        if (iterable != null) {
            iterable.forEach(s -> {
                FamilyBO bo = new FamilyBO();
                BeanUtils.copyProperties(s, bo);
                JSONObject ageJson = this.getAge(s.getBirth());
                if (ageJson != null) {
                    bo.setAge(ageJson.getInteger("age"));
                    bo.setAgeUnit(ageJson.getString("ageUnit"));
                }
                bos.add(bo);
            });

        }
        return bos;
    }

    /**
     * 给家庭成员年龄赋值 PatientFamilyServiceImpl.setFamilyLiteVOAge()
     *
     * @param familyLiteVO
     * @param birthDay
     * @Date 2018年6月2日
     * @since 2.18
     */
    private void setFamilyLiteVOAge(FamilyLiteVO familyLiteVO, Date birthDay) {
        if (familyLiteVO != null && birthDay != null) {
            JSONObject ageJson = this.getAge(birthDay);
            if (ageJson != null) {
                familyLiteVO.setAge(ageJson.getInteger("age") + ageJson.getString("ageUnit"));
            }
        }
    }

    @Override
    public FamilyVO getSelfOrBaseInfo(Long patientId) throws PatientBusinessException {
        Patient patient = this.patientDao.getPatient(patientId);
        if (patient == null) {
            LOGGER.error("patient not exist : patientId {}", patientId);
            throw new PatientBusinessException(ExceptionCodes.PATIENT_NOT_EXIST);
        }
        FamilyVO selfInfo = new FamilyVO();
        Integer selfCode = FamilyRelationEnum.RELATION_ONESELF.getValue();
        selfInfo.setRelation(selfCode);
        selfInfo.setName(StringUtils.isEmpty(patient.getName()) ? patient.getNickName() : patient.getName());
        selfInfo.setGender(patient.getGender());
        selfInfo.setPhone(patient.getPhone());
        selfInfo.setIdCard(StringUtils.isEmpty(patient.getIdCard()) ? "" : patient.getIdCard());

        if (patient.getBirthday() != null) {
            selfInfo.setBirth(patient.getBirthday().getTime());
        }
        return selfInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FamilyVO saveAndGetSelfInfo(Long patientId) throws PatientBusinessException {
        PatientFamily selfInfo = this.patientFamilyDao.getSelfInfo(patientId);
        // 如果家庭成员表中本人信息为空，则判断个人资料信息是否维护过，维护过则带入个人资料信息
        if (selfInfo == null) {
            Patient patient = this.patientDao.getPatient(patientId);
            selfInfo = this.initSelfFromBaseInfo(patient);
        }
        if (selfInfo != null) {
            FamilyVO liteVO = new FamilyVO();
            BeanUtils.copyProperties(selfInfo, liteVO);
            if (selfInfo.getBirth() != null) {
                liteVO.setBirth(selfInfo.getBirth().getTime());
            }
            liteVO.setIdCard(StringUtils.isEmpty(liteVO.getIdCard()) ? "" : liteVO.getIdCard());
            return liteVO;
        }
        return null;
    }

    @Override
    public void setVisible(Long familyId, Integer visible) throws BusinessException {
        PatientFamily family = this.patientFamilyRepository.get(familyId);
        if (family == null) {
            throw new BusinessException(ExceptionCodes.FAMILY_NOT_EXISTS);
        }
        family.setVisible(visible);
        family.setChangedAt(new Date());
        this.patientFamilyRepository.update(family);
    }

    private PatientFamily initSelfFromBaseInfo(Patient patient) {
        if (patient != null && StringUtils.isNotEmpty(patient.getName()) && patient.getBirthday() != null) {
            PatientFamily selfInfo = new PatientFamily();
            selfInfo.setPatientId(patient.getId());
            Integer selfCode = FamilyRelationEnum.RELATION_ONESELF.getValue();
            selfInfo.setRelation(selfCode);
            selfInfo.setName(patient.getName());
            selfInfo.setGender(patient.getGender());
            selfInfo.setBirth(patient.getBirthday());
            selfInfo.setPhone(patient.getPhone());
            selfInfo.setIdCard(patient.getIdCard());
            selfInfo.setVisible(PatientFamily.VISIBLE_YES);
            selfInfo.setCreatedAt(new Date());
            this.patientFamilyDao.save(selfInfo);
            return selfInfo;
        }
        return null;
    }

    /**
     * 根据出生日期计算年龄 PatientFamilyServiceImpl.getAge()
     *
     * @param birthDay
     * @return
     * @Date 2018年6月2日
     * @since 2.18
     */
    private JSONObject getAge(Date birthDay) {
        if (birthDay != null) {
            Date now = new Date();
            int differDays = DateUtil.getTotalDay(birthDay, now);
            int age = 0;
            String ageUnit = AgeUnitEunm.YEAR.getUnit();
            if (differDays >= 365) {
                age = differDays / 365;
            } else if (differDays >= 30 && differDays < 365) {
                double dage = differDays / 30.0;
                age = (int) Math.rint(dage);
                ageUnit = AgeUnitEunm.MONTH.getUnit();
            } else if (differDays >= 0 && differDays < 30) {
                double dage = differDays / 7.0;
                age = (int) Math.rint(dage);
                if (age == 0) {
                    age = 1;
                }
                ageUnit = AgeUnitEunm.WEEK.getUnit();
            }
            JSONObject json = new JSONObject();
            json.put("age", age);
            json.put("ageUnit", ageUnit);
            return json;
        }
        return null;
    }

    @Override
    public FamilyVO getFamilyById(Long familyId, Long patientId) throws PatientBusinessException {
        PatientFamily selfInfo = this.validFamily(familyId, patientId);
        FamilyVO familyVO = new FamilyVO();
        BeanUtils.copyProperties(selfInfo, familyVO);
        if (selfInfo.getBirth() != null) {
            familyVO.setBirth(selfInfo.getBirth().getTime());
        }
        return familyVO;
    }

    /**
     * 校验是否是合法家庭成员 PatientFamilyServiceImpl.validFamily()
     *
     * @param familyId
     * @param patientId
     * @return
     * @throws PatientBusinessException
     * @Date 2018年6月2日
     * @since 2.18
     */
    private PatientFamily validFamily(Long familyId, Long patientId) throws PatientBusinessException {
        PatientFamily family = this.patientFamilyDao.get(familyId);
        if (family == null || family.getPatientId() == null || family.getPatientId().longValue() != patientId) {
            LOGGER.warn("错误的成员信息，familyId : {}, patientId: {}, family: {}", familyId, patientId, family);
            throw new PatientBusinessException(ExceptionCodes.ILLEGAL_REQUEST);
        }
        return family;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertFamily(Long patientId, FamilyParamVO paramVO) throws PatientBusinessException {
        this.addFamily(patientId, paramVO, false);
    }

    private void addFamily(Long patientId, FamilyParamVO paramVO, boolean relationSource) throws PatientBusinessException {
        this.validFamilyParam(paramVO);

        //患者和家庭成员身份证唯一
        this.familyUniqChecked(patientId, paramVO.getIdCard());
        // 判断添加的是否是本人，如果本人已经存在不能再次添加；添加本人成功需要更新个人资料
        boolean addSelf = false;
        if (paramVO.getRelation() == FamilyRelationEnum.RELATION_ONESELF.getValue().intValue()) {
            PatientFamily selfInfo = this.patientFamilyDao.getSelfInfo(patientId);
            if (selfInfo != null) {
                LOGGER.warn("本人信息已经存在，添加失败， patientId: {}, family: {}", patientId, paramVO);
                throw new PatientBusinessException(ExceptionCodes.ILLEGAL_REQUEST);
            }
            addSelf = true;
        } else if (!relationSource) {
            // 校验是否已经有本人信息，如果没有则提示先添加本人信息
            PatientFamily selfInfo = this.patientFamilyDao.getSelfInfo(patientId);
            if (selfInfo == null) {
                LOGGER.warn("还未添加本人信息，添加失败， patientId: {}, family: {}", patientId, paramVO);
                throw new PatientBusinessException(ExceptionCodes.ILLEGAL_REQUEST);
            }
        }
        PatientFamily family = new PatientFamily();
        BeanUtils.copyProperties(paramVO, family);
        family.setPatientId(patientId);
        String birthStr = paramVO.getBirth();
        if (StringUtils.isNotEmpty(birthStr)) {
            Date birth = DateUtil.parseStrToDate(birthStr);
            family.setBirth(birth);
        }
        family.setVisible(PatientFamily.VISIBLE_DEFAULT);
        family.setCreatedAt(new Date());

        this.patientFamilyDao.save(family);

        // 同步本人信息
        if (addSelf) {
            Patient patient = this.patientDao.getPatient(patientId);
            if (patient != null) {
                this.syncSelfToBaseInfo(family, patient);
                patient.setChangedAt(new Date());
                this.patientDao.update(patient);
            }
        }
    }

    private void syncSelfToBaseInfo(PatientFamily family, Patient patient) throws PatientBusinessException {
        if (patient == null || family == null) {
            return;
        }
        if (!family.getName().equals(patient.getName())) {
            patient.setName(family.getName());
        }
        if (patient.getGender() == null || family.getGender() == null || patient.getGender().intValue() != family.getGender().intValue()) {
            patient.setGender(family.getGender());
        }
        Date birth = family.getBirth();
        Date baseBirth = patient.getBirthday();
        if (birth == null || baseBirth == null || birth.getTime() != baseBirth.getTime()) {
            patient.setBirthday(family.getBirth());
        }
        // 返写个人中心不返写手机号码
        // String phone = family.getPhone();
        // String basePhone = patient.getPhone();
        // if (phone == null || basePhone == null || !phone.equals(basePhone)) {
        // patient.setPhone(family.getPhone());
        // }

        String idCard = family.getIdCard();
        String baseIdCard = patient.getIdCard();
        if (idCard == null || baseIdCard == null || !idCard.equals(baseIdCard)) {
            patient.setIdCard(family.getIdCard());
        }
    }


    /**
     * 校验添加成员参数 PatientFamilyServiceImpl.validFamilyParam()
     *
     * @param paramVO
     * @throws PatientBusinessException
     * @Date 2018年6月2日
     * @since 2.18
     */
    private void validFamilyParam(FamilyParamVO paramVO) throws PatientBusinessException {
        if (paramVO == null) {
            LOGGER.warn("成员参数信息为空，paramVO: {}", paramVO);
            throw new PatientBusinessException(ExceptionCodes.ILLEGAL_REQUEST);
        }
        String name = paramVO.getName();
        //校验姓名合法
        if (!com.naiterui.ehp.bs.patient.utils.StringUtil.valRealName(name)) {
            throw new PatientBusinessException(ExceptionCodes.PATIENT_NAME_NOT_RULE);
        }
        if (!LimitValueConfig.validateLimit(LimitValueConfig.LIMIT_FAMILY_NAME, name)) {
            LOGGER.warn("家庭成员姓名不合法，name: {}", name);
            throw new PatientBusinessException(ExceptionCodes.FAMILY_NAME_ERROR);
        }

        Integer gender = paramVO.getGender();
        if (gender == null
            || (CommonConstantEnum.GENDER_FEMALE.getId().intValue() != gender && CommonConstantEnum.GENDER_MALE.getId().intValue() != gender)) {
            LOGGER.warn("家庭成员性别输入错误，gender: {}", gender);
            throw new PatientBusinessException(ExceptionCodes.ILLEGAL_REQUEST);
        }

        String birth = paramVO.getBirth();
        if (StringUtils.isEmpty(birth)) {
            LOGGER.warn("家庭成员出生日期为空，birth: {}", birth);
            throw new PatientBusinessException(ExceptionCodes.ILLEGAL_REQUEST);
        }

        String phone = paramVO.getPhone();
        if (FamilyRelationEnum.RELATION_ONESELF.getValue().equals(paramVO.getRelation()) && !StringUtil.isMobileNum(phone)) {
            LOGGER.warn("家庭成员本人电话号码格式不正确，phone: {}", phone);
            throw new PatientBusinessException(ExceptionCodes.FAMILY_PHONE_ERROR);
        }
        //修改时不校验身份证号
        if (paramVO.getFamilyId() == null) {
            String idCard = paramVO.getIdCard();
            if (StringUtils.isNotEmpty(idCard) && !IdcardUtil.isValidCard(idCard)) {
                LOGGER.warn("家庭成员身份证号格式不正确，idCard: {}", idCard);
                throw new PatientBusinessException(ExceptionCodes.FAMILY_IDCARD_ERROR);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFamily(Long patientId, Long familyId, FamilyParamVO paramVO) throws PatientBusinessException {
        this.validFamilyParam(paramVO);
        // 判断是否是该患者的家庭成员
        PatientFamily family = this.validFamily(familyId, patientId);
        BeanUtils.copyProperties(paramVO, family);
        String birthStr = paramVO.getBirth();
        if (StringUtils.isNotEmpty(birthStr)) {
            Date birth = DateUtil.parseStrToDateTime(birthStr);
            family.setBirth(birth);
        }
        family.setChangedAt(new Date());
        this.patientFamilyDao.update(family);

        // 同步本人信息
        if (paramVO.getRelation() == FamilyRelationEnum.RELATION_ONESELF.getValue().intValue()) {
            Patient patient = this.patientDao.getPatient(patientId);
            if (patient != null) {
                this.syncSelfToBaseInfo(family, patient);
                patient.setChangedAt(new Date());
                this.patientDao.update(patient);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FamilyBO insertOrUpdateSelf(Long patientId, Integer gender, String birth, String phone, String name) throws PatientBusinessException {
        // 查询个人信息
        PatientFamily selfInfo = this.patientFamilyDao.getSelfInfo(patientId);
        boolean needSync = false;
        if (selfInfo == null) {
            Patient patient = this.patientDao.getPatient(patientId);
            if (patient == null) {
                LOGGER.error("新增本人家庭成员失败，患者信息不存在。patientId: {}", patientId);
                throw new PatientBusinessException(ExceptionCodes.PATIENT_NOT_EXIST);
            }
            selfInfo = new PatientFamily();
            //String name = StringUtils.isNotBlank(patient.getName()) ? patient.getName() : patient.getNickName();
            selfInfo.setName(name);
            selfInfo.setPatientId(patientId);
            selfInfo.setGender(gender);
            selfInfo.setRelation(FamilyRelationEnum.RELATION_ONESELF.getValue());
            if (birth != null) {
                Date birthDay = DateUtil.parseStrToDateTime(birth);
                selfInfo.setBirth(birthDay);
            }
            selfInfo.setPhone(phone);
            selfInfo.setVisible(PatientFamily.VISIBLE_YES);
            selfInfo.setCreatedAt(new Date());
            this.patientFamilyDao.save(selfInfo);
            needSync = true;
        } else {
            // 如果有个人信息，判断是否变更
            String savedPhone = "";
            if (selfInfo.getPhone() != null) {
                savedPhone = selfInfo.getPhone();
            }
            if (phone == null) {
                phone = "";
            }
            String savedBirth = "";
            if (selfInfo.getBirth() != null) {
                savedBirth = DateUtil.formatDate(selfInfo.getBirth(), DateUtil.DATE_FORMAT);
            }
            Date birthDay = null;
            if (birth != null) {
                birthDay = DateUtil.parseStrToDateTime(birth);
                birth = DateUtil.formatDate(birthDay, DateUtil.DATE_FORMAT);
            }

            if (!(selfInfo.getName().equals(name)
                && selfInfo.getGender().equals(gender)
                && savedPhone.equals(phone)
                && savedBirth.equals(birth))) {
                selfInfo.setName(name);
                selfInfo.setGender(gender);
                selfInfo.setBirth(birthDay);
                selfInfo.setPhone(phone);
                selfInfo.setVisible(PatientFamily.VISIBLE_YES);
                selfInfo.setChangedAt(new Date());
                this.patientFamilyDao.update(selfInfo);
                needSync = true;
            }
        }

        // 同步个人中心信息，手机号不同步
        if (needSync) {
            Patient patient = this.patientDao.getPatient(patientId);
            if (patient != null) {
                this.syncSelfToBaseInfo(selfInfo, patient);
                patient.setChangedAt(new Date());
                this.patientDao.update(patient);
            }
        }

        FamilyBO bo = new FamilyBO();
        BeanUtils.copyProperties(selfInfo, bo);
        if (selfInfo.getBirth() != null) {
            bo.setBirth(selfInfo.getBirth().getTime());
            JSONObject ageJson = this.getAge(selfInfo.getBirth());
            if (ageJson != null) {
                bo.setAge(ageJson.getInteger("age"));
                bo.setAgeUnit(ageJson.getString("ageUnit"));
            }
        }
        return bo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertOrUpdateSelf(Patient patient) throws PatientBusinessException {
        if (patient == null) {
            return;
        }
        PatientFamily selfInfo = this.patientFamilyDao.getSelfInfo(patient.getId());
        if (selfInfo == null) {
            // 新增本人信息
            this.initSelfFromBaseInfo(patient);
        } else {
            // 更新本人信息
            this.syncBaseInfoToSelf(patient, selfInfo);
            selfInfo.setChangedAt(new Date());
            this.patientFamilyDao.update(selfInfo);
        }
    }

    private void syncBaseInfoToSelf(Patient patient, PatientFamily family) throws PatientBusinessException {
        if (patient == null || family == null) {
            return;
        }
        if (!patient.getName().equals(family.getName())) {
            family.setName(patient.getName());
        }
        if (patient.getGender() == null || family.getGender() == null || patient.getGender().intValue() != family.getGender().intValue()) {
            family.setGender(patient.getGender());
        }
        Date birth = family.getBirth();
        Date baseBirth = patient.getBirthday();
        if (birth == null || baseBirth == null || birth.getTime() != baseBirth.getTime()) {
            family.setBirth(patient.getBirthday());
        }

        String phone = family.getPhone();
        String basePhone = patient.getPhone();
        if (phone == null || basePhone == null || !phone.equals(basePhone)) {
            family.setPhone(patient.getPhone());
        }

        String idCard = family.getIdCard();
        String baseIdCard = patient.getIdCard();
        if (idCard == null || baseIdCard == null || !idCard.equals(baseIdCard)) {
            family.setIdCard(patient.getIdCard());
        }
    }

    @Override
    public FamilyBO getInnerFamilyById(Long familyId) throws PatientBusinessException {
        PatientFamily family = this.patientFamilyDao.get(familyId);
        FamilyBO familyBO = new FamilyBO();
        if (family != null) {
            BeanUtils.copyProperties(family, familyBO);
            if (family.getBirth() != null) {
                familyBO.setBirth(family.getBirth().getTime());
                JSONObject ageJson = this.getAge(family.getBirth());
                if (ageJson != null) {
                    familyBO.setAge(ageJson.getInteger("age"));
                    familyBO.setAgeUnit(ageJson.getString("ageUnit"));
                }
            }
        }
        return familyBO;
    }

    @Override
    public Integer judgeFamily(Long patientId, String name, Integer gender, Integer age, String ageUnit) throws PatientBusinessException {
        Integer relation = -1;// 没有找到对应关系
        List<PatientFamily> familyList = this.patientFamilyDao.getFamilyListByPatientId(patientId);
        if (familyList != null) {
            for (PatientFamily pf : familyList) {
                String fName = pf.getName();
                Integer fGender = pf.getGender();
                JSONObject ageJson = this.getAge(pf.getBirth());
                if (ageJson == null || fGender == null || StringUtils.isEmpty(fName)) {
                    continue;
                }
                Integer fAge = ageJson.getInteger("age");
                String fAgeUnit = ageJson.getString("ageUnit");
                // 全部相同时
                if (fName.trim().equals(name.trim()) && fGender.intValue() == gender.intValue() && fAge.intValue() == age.intValue()
                    && fAgeUnit.equals(ageUnit)) {
                    relation = pf.getRelation();
                    break;
                }
            }
        }
        return relation;
    }

    @Override
    public Integer judgeOneself(Long patientId, String name, Integer gender, Integer age, String ageUnit) throws PatientBusinessException {
        // 判断家庭成员关系
        List<PatientFamily> familyList = this.patientFamilyDao.getFamilyListByPatientId(patientId);
        // 患者本人信息
        Patient patient = this.patientDao.getPatient(patientId);

        Integer flag = RELATION_NOT;
        // 不为空，肯定有本人关系
        if (familyList != null && !familyList.isEmpty()) {
            for (PatientFamily pf : familyList) {
                String fName = pf.getName();
                Integer fGender = pf.getGender();
                JSONObject ageJson = this.getAge(pf.getBirth());
                if (ageJson == null || fGender == null || StringUtils.isEmpty(fName)) {
                    continue;
                }
                Integer fAge = ageJson.getInteger("age");
                String fAgeUnit = ageJson.getString("ageUnit");
                // 全部相同，且为本人时
                if (fName.trim().equals(name.trim()) && fGender.intValue() == gender.intValue() && fAge.intValue() == age.intValue()
                    && fAgeUnit.equals(ageUnit) && pf.getRelation() == FamilyRelationEnum.RELATION_ONESELF.getValue().intValue()) {
                    flag = RELATION_ONESELF;
                    break;
                }
            }
            // 没有找到应关系,非本人
            if (flag != RELATION_ONESELF) {
                LOGGER.info("家庭成员关系判断没有本人");
                flag = RELATION_NOT_ONSELF;
            }
        } else {
            // 姓名、性别、年龄都有时才作判断
            if (StringUtils.isNotBlank(patient.getName()) && (patient.getGender() != null && patient.getGender() != Patient.GENDER_UNKNOWN)
                && patient.getBirthday() != null) {
                String pName = patient.getName();
                Integer pGender = patient.getGender();
                JSONObject ageJson = this.getAge(patient.getBirthday());
                if (ageJson != null) {
                    Integer pAge = ageJson.getInteger("age");
                    String pAgeUnit = ageJson.getString("ageUnit");
                    // 全部相同
                    if (pName.trim().equals(name.trim()) && pGender.intValue() == gender.intValue() && pAge.intValue() == age.intValue()
                        && pAgeUnit.equals(ageUnit)) {
                        flag = RELATION_ONESELF;
                    } else {
                        LOGGER.info("基本信息判断没有本人");
                        flag = RELATION_NOT_ONSELF;
                    }
                }

            } else {
                LOGGER.info("姓名、性别、年龄基中一项为空,name:{},gender:{},birthday:{}", patient.getName(), patient.getGender(), patient.getBirthday());
            }
        }
        return flag;
    }

    private void familyUniqChecked(Long patienId, String idCard) throws PatientBusinessException {
        PatientFamily family = this.patientFamilyRepository.findFirstByPatientIdAndIdCard(patienId, idCard);
        if (family != null) {
            throw new PatientBusinessException(ExceptionCodes.FAMILY_ALREADY_EXISTS);
        }
    }


}
